// ActionScript file
import com.nstar.base.event.RequestEvent;
import com.nstar.base.util.CSSParser;
import com.nstar.base.util.EffectUtils;
import com.nstar.base.util.GraphicsUtils;
import com.nstar.base.util.LoadXMLDelegate;
import com.nstar.pum.components.ImageButton;
import com.nstar.pum.mxml.Scences;
import com.nstar.pum.mxml.SimpleToast;
import com.nstar.pum.view.Money;
import com.nstar.pum.view.MoneyFactory;

import flash.display.DisplayObject;
import flash.events.MouseEvent;
import flash.events.TimerEvent;
import flash.geom.Point;
import flash.media.SoundChannel;
import flash.net.SharedObject;
import flash.utils.Timer;

import mx.collections.ArrayCollection;
import mx.core.Application;
import mx.core.SoundAsset;
import mx.events.ItemClickEvent;
import mx.events.ListEvent;
import mx.formatters.NumberFormatter;

public static const MINUTE:Number = 1000;
public static const DEFAULT_DELAY:Number = 300;//速度
public static const DEFAULT_REPEAT_COUNT:Number = MINUTE * 0.2 *0.1;//时间

public static const TOTAL_MONEY:String = "totalMoney";
public static const GOT_MONEY:String = "gotMoney";
public static const START_GAME:String = "startGame";
public static const GAME_OVER:String = "gameOver";
public static const RESET:String = "reset";
public static const GET_MONEY_TYPE:String = "getMoneyType";
public static const NEXT_VALUE:String = "nextValue";



public static const MONEY_URL:String = "assets/money.xml";
public static const SCENCE_URL:String = "assets/scence.xml";
public static const RANGE_CHECK_URL:String = "assets/range_check.xml";
public static const SO_URL:String = "pick_up_money";

private var playing:Boolean = false;//游戏中
private var pausing:Boolean = false;//暂停中

private var total:Number = 0;//掉下来的总额
public var gotMoneys:Number = 0;//捡到的总额

private var timeLeftRate:Number = 1;//剩余时间比率
private var duration:int = Money.MAX_SPEED;//默认掉下的速度

private var timer:Timer = new Timer(DEFAULT_DELAY,DEFAULT_REPEAT_COUNT);//定时器

private var loader:LoadXMLDelegate;//加载各种类型的钞票配置数据
private var moneyList:ArrayCollection;//钞票面值列表
private var moneyPlus:ArrayCollection;//具有附加值的对象，如支票、金条等等
private var moneyMinus:ArrayCollection;//具有负的附加值的对象，捡到后gotMoneys会减去相应的值
private var pingPai:ArrayCollection;//品牌对象，这些对象具有高附加值，例如肯德基、麦当劳，或者其它品牌(广告）


private var scenceLoader:LoadXMLDelegate;//场景配置加载
private var scenceList:ArrayCollection;

private var rangeLoader:LoadXMLDelegate;//已捡钞票总额范围检查
private var rangeList:ArrayCollection;

private var values:Array;//面值列表，纯数字
private var moneys:ArrayCollection;//面值列表，包括标题、值和图片URL

private var sv:String;//选中的钞票类型

public var logined:Boolean = false;//是否登录

public var historyRecord:Number;

private var so:SharedObject;

private var app;

[Embed(source="assets/sound/rollover.mp3")]
[Bindable]            
public var Song:Class;

[Embed(source="assets/sound/spark.mp3")]
[Bindable]            
public var Spark:Class;

[Embed(source="assets/sound/blip.mp3")]
[Bindable]            
public var Blip:Class;

private var mp3:SoundAsset = new Song() as SoundAsset;
public var channel:SoundChannel;

private var spark:SoundAsset = new Spark() as SoundAsset;
private var blip:SoundAsset = new Blip() as SoundAsset;
            
private function init():void{
	app = Application.application;
	imgBg.source = CSSParser.getStyle(".background2","borderSkin");
	
	timer.addEventListener(TimerEvent.TIMER,timerHandler);
	timer.addEventListener(TimerEvent.TIMER_COMPLETE,timerHandler);
	
	loader = new LoadXMLDelegate(this,MONEY_URL,"object");
	loader.load();
	
	scenceLoader = new LoadXMLDelegate(this,SCENCE_URL,"object");
	scenceLoader.load();
	
	
	
	buttons.getChildAt(0).width = 175;
	buttons.getChildAt(1).width = 183;
	
	this.invalidateDisplayList();
}



public function result(data:Object):void{
	switch(data.token.message.url){
		case MONEY_URL:
			moneyList = data.result.moneys.money;
			//具有特殊附加值的对象
			moneyPlus = data.result.moneys.money_plus.values;//+钱
			moneyMinus = data.result.moneys.money_minus.values;//-钱
			pingPai = data.result.moneys.pingpai.values;//品牌，高价值对象
			
			//获取分类
			var idx:int = 0;
			for each(var item:Object in moneyList.toArray()){
				var box:ImageButton = new ImageButton();
				box.addEventListener(MouseEvent.ROLL_OVER,boxHandler);
				box.addEventListener(MouseEvent.ROLL_OUT,boxHandler);
				box.addEventListener(MouseEvent.CLICK,boxHandler);
				box.width = 461;
				box.height = 52;
				box.type = item.type;
				box.buttonMode = true;
				box.source = item.skin;
				box.toolTip = item.label;
				boxMoneyType.addChild(box);
				
				idx++;
			}		
			break;
		case SCENCE_URL:
			scenceList = data.result.scences.scence;
			break;
		case RANGE_CHECK_URL:
			rangeList = data.result.ranges.range;
			//初始设置为锁定状态
			for each(var item:Object in rangeList.toArray()){
				item.locked = item.stage>historyRecord;
			}
			//根据之前的历史记录，放开相应的关卡
			
			
			listLevels.dataProvider = rangeList;
			break;
	}

}


public function fault(info:Object):void{
	trace("error");
}

public function updateRecord(score:Number):void{
	this.historyRecord = score;
	
	rangeLoader = new LoadXMLDelegate(this,RANGE_CHECK_URL,"object");
	rangeLoader.load();	
}

private function boxHandler(event:MouseEvent):void{
	switch(event.type){
		case MouseEvent.CLICK:
			if(logined==false){
				SimpleToast.showMsg("要先使用新浪微博帐号登录哦~");
				return;
			}
			sv = ImageButton(event.currentTarget).type;
			readyHandler(null);
			break;
		case MouseEvent.ROLL_OVER:
			playSound(mp3);
			EffectUtils.setFlowEffect(event.target,0xFFFF00);
			break;
		case MouseEvent.ROLL_OUT:
			stopSound();
			event.target.filters = null;
			break;
	}	
}

public function playSound(mp3:SoundAsset):void 
{
    stopSound();
    channel = mp3.play();
}            
public function stopSound():void 
{
    if ( channel != null ) channel.stop();
}

//更换游戏场景
private function changeScence(event:ListEvent):void{
	//imgBack.source = cboScences.value;
}

//选择钞票类型后切换到开始游戏场景
private function readyHandler(event:ItemClickEvent):void{
	vsMain.selectedIndex = 2;

	values = getSelectedValues();
	moneys = getSelectedMoneys();
	
	//根据历史记录确定要添加的其它面值
	addSpecMoney2List(this.historyRecord);	
	
	this.dispatchEvent(new RequestEvent(GET_MONEY_TYPE,moneys));
}

//开始游戏
private function startHandler(nextStage:Boolean):void{
	if(sv==null){
		SimpleToast.showMsg("请先选择一种钞票哦");
		vsMain.selectedIndex = 0;
		return;
	}
	
	//隐藏开始和重新开始按钮，显示暂停按钮，并设置开始按钮的位置
	btnStart.visible = btnStart.includeInLayout = false;
	btnStart.setStyle("horizontalCenter",-(btnStart.width/2 -10));
	btnRestart.visible = btnRestart.includeInLayout = false;
	btnPause.visible = btnPause.includeInLayout = true;
	
	start(nextStage);
}

//开始
private function start(nextStage:Boolean):void{
	
	if(playing==false){
		duration = Money.MAX_SPEED;//只在重新开始时才会重新设置速度
	}
	
	//重新开始时计时器重置
	if(pausing==false){
		timer.reset();
		this.dispatchEvent(new RequestEvent(START_GAME,nextStage));
	}
	
	timer.start();
	
	playing = true;
	allowClickHandler(true);//允许捡钞票
	EffectUtils.resumeAllTweens();//清除之前所有的效果
}

//重新开始
private function restartHandler():void{
	this.reset(true);
	startHandler(false);
}

//暂停操作
public function pauseHandler():void{
	btnStart.styleName = "continueButton";
	btnStart.width = 215;
	btnStart.height = 75;
	btnStart.visible = btnStart.includeInLayout = true;
	btnRestart.visible = btnRestart.includeInLayout = true;
	btnPause.visible = btnPause.includeInLayout = false;
	
	pause();
}


//暂停
private function pause():void{
	EffectUtils.pauseAllTweens();
	timer.stop();
	pausing = true;
	
	//暂停状态下不能再捡
	allowClickHandler(false);
}

//停止当前游戏
public function stopStageHandler():void{
	timer.stop();
	timer.reset();
	this.reset(false);
}

//定时器事件处理
private function timerHandler(event:TimerEvent):void{
	switch(event.type){
		case TimerEvent.TIMER:
			//倒计时间
			var allTime:Number = ((DEFAULT_DELAY * DEFAULT_REPEAT_COUNT) / MINUTE);
			var passedTime:Number = timer.currentCount  * (DEFAULT_DELAY / MINUTE);
			var nf:NumberFormatter = new NumberFormatter();
			nf.precision = 0;
			lblTime.text = nf.format(allTime-passedTime);
			
			duration--;//速度
			if(duration<Money.MIN_SPEED) duration = Money.MIN_SPEED;
			
			//添加特殊的面值
			addSpecMoney2List(app.score);
			
			//生成随机的钞票，从天上掉下来
			var money:Money = MoneyFactory.createRandomMoney(rbgMoneyType.selectedValue as String,values,duration,moneys.toArray());
			money.addEventListener(Money.CURRENT_MONEY,moneyHandler);
			money.addEventListener(Money.REMOVE_MONEY,moneyHandler);
			money.addEventListener(Money.CLICKED_MONEY,moneyHandler);
			
			canvas.addChild(money);
			break;
		case TimerEvent.TIMER_COMPLETE://游戏结束
			reset(false);
			this.dispatchEvent(new RequestEvent(GAME_OVER,null));
			break;
	}
}

//捡钞票处理
private function moneyHandler(event:RequestEvent):void{
	if(!playing) return;
	
	switch(event.type){
		case Money.CURRENT_MONEY:
			//剩余时间比率
			timeLeftRate = (timer.currentCount*timer.delay)/(timer.repeatCount*timer.delay);
			timeBar.width = timeWidth.width - timeWidth.width*timeLeftRate;
			
			var v:Number = event.request as Number;
			if(v>0){
				this.dispatchEvent(new RequestEvent(TOTAL_MONEY,numberFormatter.format(v)));
			}
			
			break;
		case Money.CLICKED_MONEY:
			
			gotMoneys = event.request as Number;//累计捡到的
			var req:Object = new Object();
			req.gotMoneys = gotMoneys;
			req.value = event.request;
			this.dispatchEvent(new RequestEvent(GOT_MONEY,req));
			
			if(gotMoneys<0){
				playSound(blip);//捡到减钱的对象
			}else{
				playSound(spark);
			}
			
			break;
		case Money.REMOVE_MONEY:
			var o:DisplayObject = event.request as DisplayObject;
			var p = o.parent;
			if(p)
				p.removeChild(o);
			
			break;
	}
	
}


//获取当前选中的币种的各种面值
private function getSelectedValues():Array{
	var ary:Array = new Array();
	//var sv:String = rbgMoneyType.selectedValue;
	for(var i:int =0;i<moneyList.length;i++){
		if(moneyList.getItemAt(i).type==sv){
			var list:ArrayCollection = moneyList.getItemAt(i).values;
			for(var j:int;j<list.length;j++){
				ary.push(list.getItemAt(j).value);
			}
		}
	}
	
	//添加特殊的面值
	for each(var item:Object in moneyMinus.toArray()){
		ary.push(item.value);
	}
		
	return ary;
}

//获取当前选中的币种面值列表
private function getSelectedMoneys():ArrayCollection{
	var ary:ArrayCollection = new ArrayCollection();
	for(var i:int =0;i<moneyList.length;i++){
		if(moneyList.getItemAt(i).type==sv){
			var list:ArrayCollection = moneyList.getItemAt(i).values;
			for (var j:int = 0;j<list.length;j++){
				ary.addItem(list.getItemAt(j));
			}
			 
			//添加负面值
			for each(var item:Object in moneyMinus.toArray()){
				ary.addItem(item);
			}
			
			
			for(var j:int=0;j<ary.length;j++){
				ary.getItemAt(j).count = 0;//设置初始值
			}
			
			return ary;
		}
	}
	return null;
}

//根据当前捡到的钞票总额，来添加特定面值的对象，例如支票、品牌(高价值)
public function addSpecMoney2List(score:Number):void{
	var list:Array = getMoneysByValue(score);
	trace("added "+list.length+" moneys");
	for each(var item:Object in list){
		moneys.addItem(item);
	}
	
	//添加面值列表
	if(list){
		for each(var item:Object in list){
			values.push(item.value);
		}
	}
}

//从具有附加值对象中获取指定的value对象
private function getMoneysByValue(score:Number):Array{
	var ary:Array = new Array();
	var value:Number = 0;
	var nextValue:Number = 0;
	var valueList:Array = new Array();
	
	//获取范围检查值
	for (var i:int = 0;i<rangeList.length;i++){
		var stage:Number = rangeList.getItemAt(i).stage;
		if(score>stage){
			nextValue = rangeList.getItemAt(i).next_value;
			value = stage;
			valueList.push(value);
		}
	}
	
	trace("valueList="+valueList);
	
	//检查value是否已经存在面值列表中，在的话就不再添加
	for each(var v:Number in valueList){
		if(v==0 || values.indexOf(v)!=-1) continue;
		
		
		//从Plus中获取面值为value的money
		var item:Object ;
		for (var i:int = 0;i<moneyPlus.length;i++){
			item = moneyPlus.getItemAt(i);
			if(item.value == v){
				item.count = 0;
				ary.push(item);
			}
		}
		//从PingPai中获取面值为value的money
		for (var i:int = 0;i<pingPai.length;i++){
			item = pingPai.getItemAt(i);
			if(item.value == v){
				item.count = 0;
				ary.push(item);
			}
		}
	}
	
	

	var req:Object = new Object();
	req.value = getNextValue(nextValue);
	req.names = getNextNames(req.value as Number);
	this.dispatchEvent(new RequestEvent(NEXT_VALUE,req));
	return ary;
}

//取得下个出现的值
private function getNextValue(value:Number):Number{
	for (var i:int =0;i<rangeList.length;i++){
		var nextValue:Number = rangeList.getItemAt(i).next_value;
		if(nextValue>value) return nextValue;
	}
	return 0;
}

//取得下一个面值为value的品牌名称列表
private function getNextNames(v:Number):String{
	var names:String = "";
	var item:Object ;
	for (var i:int = 0;i<moneyPlus.length;i++){
		item = moneyPlus.getItemAt(i);
		if(item.value == v){
			names += item.label+",";
		}
	}
	//从PingPai中获取面值为value的money
	for (var i:int = 0;i<pingPai.length;i++){
		item = pingPai.getItemAt(i);
		if(item.value == v){
			names += item.label+",";
		}
	}
	if(names.indexOf(",")!=-1){
		names = names.substr(0,names.length-1);
	}
	
	return names;
}

//复位
private function reset(dispEvent:Boolean):void{
	canvas.removeAllChildren();
	total = 0;
	gotMoneys = 0;
	duration = Money.MAX_SPEED;
	playing = false;
	pausing = false;
	timeBar.width = timeWidth.width;
	btnPause.visible = btnPause.includeInLayout = false;
	btnStart.visible = btnStart.includeInLayout = true;
	btnStart.setStyle("horizontalCenter",0);
	if(dispEvent)
		this.dispatchEvent(new RequestEvent(RESET,null));
}

//是否允许捡
private function allowClickHandler(allowed:Boolean):void{
	for each(var item:Money in canvas.getChildren()){
		item.dispatchEvent(new RequestEvent(Money.ALLOW_CLICKED,allowed));
	}
}

//币种类型名称
public function get moneyType():String{
	switch(rbgMoneyType.selectedValue){
		case MoneyFactory.M_RMB:
			return "元";
			break;
		case MoneyFactory.M_US:
			return "美元";
			break;
		case MoneyFactory.M_EURO:
			return "欧元";
	}
	return "元";
}

//显示场景菜单列表
private function showScenceList(event:MouseEvent):void{
	var p:Point = event.target.localToGlobal(new Point());
	var scence:Scences = Scences.show(p.x,p.y+event.target.height-3,scenceList.toArray(),imgBack.source as String);
	scence.addEventListener(Scences.CHANGE_SCENCE,changeScenceHandler);
}

private function changeScenceHandler(event:RequestEvent):void{
	imgBack.source = event.request.data;
}

private function selectLevelHandler(event:ListEvent):void{
	if(listLevels.selectedItem.locked == false){
		vsMain.selectedIndex = 1;
	}
}

//检查当前关卡是否完成
public function isClearStage(gotMoneys:Number):Boolean{
	var idx:int = listLevels.selectedIndex+1;
	if(idx<listLevels.dataProvider.length){
		var stage:Number = listLevels.dataProvider[idx].stage;
		return gotMoneys>stage;
	}else{
		return false;
	}
}

//刷新关卡数据状态
public function refreshLevel():void{
	var idx:int = listLevels.selectedIndex;
	if(idx<listLevels.dataProvider.length-1){
		listLevels.dataProvider[idx+1].locked = false;
		listLevels.selectedIndex = idx+1;
	}
}



override protected function updateDisplayList(unscaledWidth:Number,unscaleHeight:Number):void{
	super.updateDisplayList(unscaledWidth,unscaleHeight);
	GraphicsUtils.drawBackground(imgBg,boxMoneyType);
}

